
#include "xapp_config.h"

#if USER_CHECK_ENABLED( BUTTON )

#include "xapp_button.h"
#include "xtask+app.h"
#include "xapp_osllv.h"

#include "em_buttons.h"

#if USER_CHECK_LOG_ENABLED( BUTTON )
#include "log.h"
#define LOG     LOG_INFO 
#define LOG0    LOG_INFO0 
#define LOG1    LOG_INFO1
#define LOG2    LOG_INFO2
#define LOG3    LOG_INFO3
#else 
#define LOG(...) 
#define LOG0(...)
#define LOG1(...)
#define LOG2(...)
#define LOG3(...)
#endif 

#if OSLLV_LCD_OUTPUT_ENABLE && OSLLV_LCD_USE_GUI
#include "gui.h"
#endif

#if BUTTON_USE_CUSTOM_HANDLE
#include BUTTON_CUSTOM_FUNC_FILE
#endif 

static void hub_button_event_handler( kb_evt_t * evt )
{
    msg_t msg;
    msg.type        = MSG_TYPE_BUTTON;
    msg.sub_type     = (evt->idx << 8) | evt->type;
    xtask_app_send_msg( &msg, __LINE__ );
}

void xapp_button_init(void)
{
    em_buttons_init();
    em_buttons_register_callback( (kb_evt_handle_t)hub_button_event_handler );
    em_buttons_start();
}


void xapp_button_msg_handler( msg_t * p_msg )
{
    kb_evt_t evt;
    evt.idx = p_msg->sub_type >> 8;
    evt.type = (kb_evt_type_t)(p_msg->sub_type & 0xff);
    
    if( evt.idx == KB_ALL_KEY && evt.type == KB_EVT_RELEASE )
    {
        LOG0("[BUTTON]: all release\r\n");
        return;
    }
    LOG2("[BUTTON]: idx=%d type=%d\r\n", evt.idx, evt.type );
    
#if BUTTON_USE_CUSTOM_HANLDE_BEGIN
    if( BUTTON_CUSTOM_HANDLE_BEGIN( &evt ) == false )
    {
        return; 
    }
#endif 

#if OSLLV_LCD_OUTPUT_ENABLE && OSLLV_LCD_USE_GUI
    gui_on_button_event( &evt );
#endif 

#if BUTTON_USE_CUSTOM_HANDLE_END
    BUTTON_CUSTOM_HANDLE_END( &evt );
#endif 
}

#endif
